import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
// import { ElMessage  } from 'element-plus';
import { getToken } from './auth';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 引入baseURL
const BASE_URL = import.meta.env.VITE_APP_BASE_API


// 创建axios实例
const service = axios.create({
  // baseURL: 'mock',
  baseURL: BASE_URL,
  withCredentials: true,
  timeout: 10000,
})

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers = {
        ...config.headers,
        Authorization: token
      }
    }
    return config
  },
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    let res = response.data as ResData<any>
    // 正常响应
    if (res.code == 0) {
      return res.result || true
    } else if (res.code == -1) {    
      ElMessage.error(res.message)
      return undefined
    }
  }
)

const request = <T = any>(
  config: AxiosRequestConfig | string,
  options?: AxiosRequestConfig,
): Promise<T> => {
  if (typeof config === 'string') {
    if (!options) {
      return service.request<T, T>({
        url: config,
      });
      // throw new Error('请配置正确的请求参数');
    } else {
      return service.request<T, T>({
        url: config,
        ...options,
      });
    }
  } else {
    return service.request<T, T>(config);
  }
};
export function get<T = any>(config: AxiosRequestConfig, options?: AxiosRequestConfig): Promise<T> {
  return request({ ...config, method: 'GET' }, options);
}

export function post<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig,
): Promise<T> {
  return request({ ...config, method: 'POST' }, options);
}

export default request
export type { AxiosInstance, AxiosResponse };